// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package iomisc

import (
	"io"
)

type multiWriter struct {
	writers []io.Writer
}

func (t *multiWriter) Write(p []byte) (n int, err error) {
	for i, w := range t.writers {
		if w == nil {
			continue
		}
		n, err = w.Write(p)
		if err != nil {
			t.writers[i] = nil
			continue
		}
		if n != len(p) {
			// Ignore short writes
			// err = io.ErrShortWrite
			continue
		}
	}
	return len(p), nil
}

// MultiWriter creates a writer that duplicates its writes to all the provided
// writers. Unlike io.MultiWriter, this one will process writes even if the
// writers are broken, making sure that writes to this writer never block.
func MultiWriter(writers ...io.Writer) io.Writer {
	return &multiWriter{writers}
}
